import { ReadonlyRequestCookies } from 'next/dist/server/web/spec-extension/adapters/request-cookies'

/**
 * @description 请求器配置项
 *
 * @param method - 请求方法
 * @param data - POST 请求体
 * @param headers - 请求头
 * @param cookieStore - 在服务器组件中使用 `cookie()` 获取的 cookieStore，用于获取当前语言信息
 */
interface FetcherOptions<D> {
  method?: RequestInit['method']
  data?: D
  headers?: HeadersInit
  cookieStore?: ReadonlyRequestCookies
}

export async function fetcher<R, D = void>(
  url: string,
  options?: FetcherOptions<D>
) {
  const baseUrl = 'http://jdcr.tykhrs.site'

  let currentLanguage = options?.cookieStore?.get('NEXT_LOCALE')?.value
  if (currentLanguage === 'tr') {
    currentLanguage = 'tu'
  }

  const res = await fetch(`${baseUrl}${url}`, {
    method: options?.method || 'GET',
    headers: {
      Accept: 'application/json',
      language: currentLanguage,
      ...options?.headers,
    } as HeadersInit,
    mode: 'cors',
    body: options?.data ? JSON.stringify(options?.data) : undefined,
  })

  if (!res.ok) {
    const errorBody = await res.text()
    throw new Error(`Failed to fetch data: ${errorBody}`)
  }

  if (!res.headers.get('content-type')?.includes('application/json')) {
    throw new Error('Not a JSON response')
  }

  const json = await res.json()

  return json.data as R
}
